import {createRouter, createWebHashHistory} from "vue-router";
import {routeMeta, routes} from "./routes";
import {useAuthStore} from "@/store/index.js";
import {useUserStore} from "@/store/user/index.js";
import userApi from "@/api/sys/user.js";
import {filterRoutesByPermission} from "@/utils/index.js";

// 创建路由实例
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: routeMeta.path.HOME,
            name: routeMeta.name.HOME,
            component: () => import('@/views/home.vue')
        },
        {
            path: routeMeta.path.LOGIN,
            name: routeMeta.name.LOGIN,
            component: () => import('@/views/login.vue')
        }
    ]
})

// 导航守卫
router.beforeEach(async (to, from, next) => {
    // 这里可以添加权限验证逻辑
    const authStore = useAuthStore()
    if (to.name !== routeMeta.name.LOGIN) {
        if (!authStore.isAuthenticated) {
            // 如果未登录且访问的不是登录页，重定向到登录页
            next({
                name: routeMeta.name.LOGIN,
                // 保存原始目标路径
                query: {redirect: to.fullPath}
            })
            return
        }
        const userStore = useUserStore()
        // 如果用户没有初始化，则初始化用户
        if (!userStore.isUserInitialized) {
            try {
                const res = await userApi.profile()
                userStore.setUserInfo(res.data)
                const permissions = userStore.permissionList || []
                const validRoutes = filterRoutesByPermission(routes, permissions)

                // 动态路由挂到 HOME（根路由）下
                validRoutes.forEach(route => {
                    router.addRoute(routeMeta.name.HOME, route)
                })
                // 404 页面必须最后添加
                router.addRoute({
                        path: routeMeta.path.NOT_FOUND,
                        name: routeMeta.name.NOT_FOUND,
                        component: () => import('@/views/error/404.vue')
                    })
                return next({...to, replace: true})
            } catch (error) {
                authStore.logout()
                // 获取用户信息失败，重新登陆
                next({
                    name: routeMeta.name.LOGIN,
                    // 保存原始目标路径
                    query: {redirect: to.fullPath}
                })
                return
            }
        }
    }
    // 如果已登录且访问登录页，重定向到首页
    if (to.name === routeMeta.name.LOGIN && authStore.isAuthenticated) {
        next({name: routeMeta.name.HOME})
        return
    }
    next()
})

export default router